<?php
declare (strict_types = 1);

namespace app\controller;

use app\middleware\Auth;
use app\model\Blogs;
use app\model\Categories;
use app\model\Comments;
use app\model\Users;
use think\exception\ValidateException;
use think\facade\Session;
use think\Request;
use think\facade\View;

class Blog
{
    // 权限验证使用中间件
    protected $middleware = [
        Auth::class => ['except' => ['read']],
    ];

    // 发布博客页面
    public function create()
    {
        return View::fetch('blog/create');
    }

    // 发布博客
    public function save(Request $request)
    {
        $title = $request->param('title');
        $category_id = $request->param('categories');
        $content = $request->param('content');

        $data = [
            'title' => $title,
            'category_id' => $category_id,
            'content' => $content,
            'user_id' => Session::get('uid'),
            'created_at' => date('Y-m-d h:i:s', time()),
            'updated_at' => date('Y-m-d h:i:s', time())
        ];

        // 验证发布内容
        try {
            validate(\app\validate\Blog::class)->batch(true)->check($data);
        } catch (ValidateException $e){
            // 获取错误信息
            $errors_arr = $e->getError();
            $errors = '';

            // 将错误信息遍历拼接成一个字符串
            foreach ($errors_arr as $error)
            {
                $errors = $errors.$error.'<br>';
            }

            // 返回错误信息
            return json(['code' => 400, 'msg' => $errors]);
        }

        // 插入数据库
        Blogs::insert($data);

        return json(['code' => 200, 'msg' => '发布成功']);
    }


    public function read(Blogs $blogs, $id)
    {
        // 获取博客
        $blog = $blogs->with('comments.users')->where('id', $id)->find();

        // 获取同类博客数量
        $cid = $blogs->where('id', $id)->value('category_id');
        $blog_count = $blogs->where('category_id', $cid)->count();

        // 获取评论数量
        $comment_count = Comments::where('blog_id', $id)->count();

        // 浏览量自增
        Blogs::where('id', $id)->inc('view')->update();

        return View::fetch('/blog/show', [
            'blog' => $blog,
            'count' => $blog_count,
            'comment_count' => $comment_count,
        ]);
    }

    public function edit($id)
    {
        // 博客标签
        $title = Blogs::where('id', $id)
            ->value('title');
        // 当前博客分类id
        $category_id = Blogs::where('id', $id)
            ->value('category_id');
        // 所有分类名和id的数据集
        $categories = Categories::select();
        // 博客正文
        $content = Blogs::where('id', $id)
            ->value('content');

        return View::fetch('/blog/edit',[
            'title' => $title,
            'categories' => $categories,
            'category_id' => $category_id,
            'content' => $content,
            'blog_id' => $id
        ]);
    }

    // 更新博客
    public function update(Request $request, $id)
    {
        $title = $request->param('title');
        $category_id = $request->param('category_id');
        $content = $request->param('content');
        $data = [
            'title' => $title,
            'category_id' => $category_id,
            'content' => $content,
            'updated_at' => date('Y-m-d h:i:s', time())
        ];

        // 验证发布内容
        try {
            validate(\app\validate\Blog::class)->batch(true)->check($data);
        } catch (ValidateException $e){
            // 获取错误信息
            $errors_arr = $e->getError();
            $errors = '';

            // 将错误信息遍历拼接成一个字符串
            foreach ($errors_arr as $error)
            {
                $errors = $errors.$error.'<br>';
            }

            // 返回错误信息
            return json(['code' => 400, 'msg' => $errors]);
        }

        $res = Blogs::where('id', $id)
            ->update($data);

        return json(['code' => 200, 'msg' => '修改成功']);
    }

    // 删除博客
    public function delete($id)
    {
        $blog = Blogs::where('id', $id)->find();
        $res = $blog->delete();

        if ($res) {
            return json(['code' => 200, 'msg' => '删除成功']);
        } else {
            return json(['code' => 400, 'msg' => '删除失败']);
        }
    }

    // 改变博客发布状态
    public function status($id)
    {
        $blog = Blogs::where('id', $id)->find();
        $blog->status = $blog->status == 1 ? 0 : 1;
        $res = $blog->save();
        if ($res){
            $msg = $blog->status == 1 ? '发布成功' : '取消发布';
            return json(['code' => 200, 'msg' => $msg]);
        } else {
            return json(['code' => 400, 'msg' => '更改失败']);
        }
    }
}
